package com.hdl.school.application;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.hdl.school.bean.User;
import com.hdl.school.receiver.Receiver1;
import com.hdl.school.receiver.Receiver2;
import com.hdl.school.schoolcontroller.BuildConfig;
import com.hdl.school.service.Service1;
import com.hdl.school.service.Service2;
import com.hdl.school.utils.TCWManager;
import com.hdl.school.utils.TimeUtil;
import com.leectrl.bean.ZigbeeDevice;
import com.leectrl.utils.DbUtil;
import com.leectrl.utils.HexUtil;
import com.liulishuo.filedownloader.FileDownloader;
import com.marswin89.marsdaemon.DaemonApplication;
import com.marswin89.marsdaemon.DaemonConfigurations;
import com.tencent.bugly.crashreport.CrashReport;

import org.apache.commons.codec.digest.DigestUtils;
import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Created by yunjian on 16/10/9.
 */
public class MyApplication extends DaemonApplication {

    public static MyApplication myApplication;
    public boolean mediaPlaying = false;
    public boolean isAudioPlaying = false;
    public static long timeoffset = 0;

    private DbManager.DaoConfig daoConfig;

    public DbManager.DaoConfig getDaoConfig() {
        return daoConfig;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(this);
        strategy.setCrashHandleCallback(new CrashReport.CrashHandleCallback() {
            public Map<String, String> onCrashHandleStart(int crashType, String errorType,
                                                          String errorMessage, String errorStack) {
                try {
                    String info="time:"+ TimeUtil.getCurTimeToString(null)+"\n";
                    info+=("errorMessage:"+errorMessage+"\r\n");
                    info+=("errorStack:"+errorStack+"\r\n");
                    info+="\r\n\r\n\r\n";
                    File file=new File(Environment.getExternalStorageDirectory()+ File.separator+"crash.log");
                    if(!file.exists()){
                        file.createNewFile();
                    }else{
                        FileInputStream fis = new FileInputStream(file);
                        int size = fis.available();
                        if(size>300*1024*1024){
                            file.delete();
                            file.createNewFile();
                        }
                    }
                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(info.getBytes());
                    fos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
                LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
                return map;
            }

            @Override
            public byte[] onCrashHandleStart2GetExtraDatas(int crashType, String errorType,
                                                           String errorMessage, String errorStack) {
                try {
                    return "Extra data.".getBytes("UTF-8");
                } catch (Exception e) {
                    return null;
                }
            }

        });
        CrashReport.initCrashReport(this, "7a5c989528" , true, strategy);
        ParserConfig.getGlobalInstance().setSafeMode(true);
        SharedPreferences sharedPreferences = getAppContext().getSharedPreferences("school_iot", 0);
        //timeoffset = sharedPreferences.getLong("timeoffset", 0);
        x.Ext.init(this);
        x.Ext.setDebug(BuildConfig.DEBUG);
        daoConfig = new DbManager.DaoConfig()
                .setDbName("school_terminal")//创建数据库的名称
                .setDbVersion(1);
        daoConfig.setDbUpgradeListener(new DbManager.DbUpgradeListener() {
            @Override
            public void onUpgrade(DbManager db, int oldVersion, int newVersion) throws DbException {
                if(newVersion==2){
                    db.addColumn(ZigbeeDevice.class,"enable_tag");
                }

            }
        });
        FileDownloader.init(this);
        DbUtil.init(this, daoConfig);
        User user = new User();
        user.setName("默认账号");
        user.setAccount("DMTadmin");
        user.setStatus(1);
        user.setDeleteTag(0);
        user.setPwd("CALK" + HexUtil.bytes2HexString(DigestUtils.sha1("admin123@")).toLowerCase() + "@2020");
        user.setCreateTime(new java.sql.Date(System.currentTimeMillis()));
        try {
            DbManager dbManager = DbUtil.getInstance();
            if (dbManager != null) {
                dbManager.replace(user);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
        String networkConfig = sharedPreferences.getString("networkConfig", null);
        if (networkConfig != null) {
            String[] networkConfigInfo = networkConfig.split(",");
            TCWManager.getInstance(MyApplication.myApplication).setNetworkInfo(networkConfigInfo[0], networkConfigInfo[1], networkConfigInfo[2], networkConfigInfo[3]);
        }
    }


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    JSONObject jsonObject = (JSONObject) msg.obj;
                    String ip = jsonObject.getString("locip");
                    String getway = jsonObject.getString("locgetway");
                    String netmask = jsonObject.getString("locmask");
                    String dns = jsonObject.getString("locdns");
                    TCWManager.getInstance(MyApplication.myApplication).setNetworkInfo(ip, netmask, getway, dns);
                    SharedPreferences sharedPreferences = getAppContext().getSharedPreferences("school_iot", 0);
                    sharedPreferences.edit().putString("networkConfig", ip + "," + netmask + "," + getway + "," + dns).commit();
                    break;
                case 6:
                    //中控升级固件
                    Intent intent1 = new Intent("com.leectrl.app.update");
                    intent1.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                    intent1.putExtra("mediaUrl", (String) msg.obj);
                    intent1.putExtra("installPackageName", "com.hdl.school.schoolcontroller");
                    sendBroadcast(intent1);
                    break;
            }
        }
    };


    @Override
    protected DaemonConfigurations getDaemonConfigurations() {
        DaemonConfigurations.DaemonConfiguration configuration1 = new DaemonConfigurations.DaemonConfiguration(
                "com.marswin89.marsdaemon.demo",
                Service1.class.getCanonicalName(),
                Receiver1.class.getCanonicalName());

        DaemonConfigurations.DaemonConfiguration configuration2 = new DaemonConfigurations.DaemonConfiguration(
                "com.marswin89.marsdaemon.demo:process2",
                Service2.class.getCanonicalName(),
                Receiver2.class.getCanonicalName());

        DaemonConfigurations.DaemonListener listener = new MyDaemonListener();
        //return new DaemonConfigurations(configuration1, configuration2);//listener can be null
        return new DaemonConfigurations(configuration1, configuration2, listener);
    }


    class MyDaemonListener implements DaemonConfigurations.DaemonListener {
        @Override
        public void onPersistentStart(Context context) {
        }

        @Override
        public void onDaemonAssistantStart(Context context) {
        }

        @Override
        public void onWatchDaemonDaed() {
        }
    }


    public static String getCurrentTime() {
        long time = (new Date()).getTime() + timeoffset;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        return sdf.format(new Date(time));
    }


    public static MyApplication getAppContext() {
        return myApplication;
    }

    public boolean isMediaPlaying() {
        return mediaPlaying;
    }

    public void setMediaPlaying(boolean mediaPlaying) {
        this.mediaPlaying = mediaPlaying;
    }

    public boolean isAudioPlaying() {
        return isAudioPlaying;
    }

    public void setAudioPlaying(boolean audioPlaying) {
        isAudioPlaying = audioPlaying;
    }
}
